package com.xiaolin.ssosystem.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.hash.BloomFilter;
import com.xiaolin.ssosystem.constants.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * @author xiaolin
 * @description 黑白名单过滤
 * @since 2024/10/17
 */
@Component
public class SSOInterceptor implements HandlerInterceptor {

    @Resource(name = "whiteIpBloomFilter")
    private BloomFilter<String> whiteIpBloomFilter;

    @Resource(name = "blackIpBloomFilter")
    private BloomFilter<String> blackIpBloomFilter;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIp = getClientIp(request);
        // 1.判断IP是否在黑名单过滤器中，如果不在，则往下走
        if (blackIpBloomFilter.mightContain(clientIp)) {
            // 2.判断Redis的IP黑名单列表是否包含这个IP，如果包含,则拦截请求，否则往下走
            Set<String> blackIps = stringRedisTemplate.opsForSet().members(RedisKey.BLACK_IP);
            if (!CollectionUtils.isEmpty(blackIps) && blackIps.contains(clientIp)) {
                return false;
            }
        }
        // 3.判断IP是否在白名单过滤器中，如果IP不在白名单过滤器中，则拦截请求，否则往下走
        if (!whiteIpBloomFilter.mightContain(clientIp)) {
            return false;
        }
        // 4.判断Redis的IP白名单列表是否包含这个IP，如果未包含，则拦截请求，否则往下走
        Set<String> whiteIps = stringRedisTemplate.opsForSet().members(RedisKey.WHITE_IP);
        if (CollectionUtils.isEmpty(whiteIps) || !whiteIps.contains(clientIp)) {
            return false;
        }
        return true;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HttpServletRequest对象
     * @return 客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP地址是客户端真实IP,多个IP地址用逗号分隔
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0];
        }
        return ipAddress;
    }
}
